from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q
from app.controllers.mini.topic import mini_topic_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.utils.upload import upload_image,upload_file
from app.schemas.mini import *

mini_topic_router = APIRouter()
model_name = "专题页"


@mini_topic_router.get("/list", summary=f"查看{model_name}列表")
async def do_settings_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        name: str = Query(None, description=f"{model_name}名称"),
):
    q = Q()
    if name:
        q &= Q(name__contains=name)
    total, data = await mini_topic_controller.do_list(page=page, page_size=page_size, search=q)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@mini_topic_router.get("/get", summary=f"查看{model_name}")
async def do_settings_get(
        data_id: int = Query(..., description="ID"),
):
    data = await mini_topic_controller.do_detail(data_id=data_id)
    return Success(data=data)

@mini_topic_router.post("/create", summary=f"创建{model_name}")
async def do_settings_create(
        data_in: MiniTopicCreate,
):
    await mini_topic_controller.do_create(obj_in=data_in)
    return Success(msg="创建成功")

@mini_topic_router.post("/update", summary=f"更新{model_name}")
async def do_settings_update(
        data_in: MiniTopicUpdate,
):
    await mini_topic_controller.do_update(obj_in=data_in)
    return Success(msg="更新成功")

@mini_topic_router.delete("/delete", summary=f"删除{model_name}")
async def do_settings_delete(
        data_id: int = Query(..., description="ID"),
):
    await mini_topic_controller.do_delete(data_id=data_id)
    return Success(msg="删除成功")


@mini_topic_router.post("/file", summary="上传缩略图")
async def file_content(file: UploadFile):
    url = await upload_image(file,"mini/topic")
    if not url:
        return Fail(code=400, msg="图片格式错误")
    data = {"url": url}
    return Success(data=data)